<template>
  <div class="weather-widget" @click="$emit('click')">
    <template v-if="loading">
      <van-loading type="spinner" size="16px" />
    </template>
    <template v-else-if="error">
      <van-icon name="warning-o" size="16px" color="#ee0a24" />
    </template>
    <template v-else>
      <div class="weather-icon">
        <van-icon :name="getWeatherIcon(weather.weather)" size="18px" />
      </div>
      <div class="weather-info">
        <span class="temperature">{{ weather.temperature }}°</span>
        <span class="city">{{ weather.city }}</span>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { get } from '../../utils/request'

const props = defineProps({
  autoLoad: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['click', 'loaded', 'error'])

const weather = ref({
  city: '',
  temperature: 0,
  weather: '',
  humidity: 0,
  icon: ''
})
const loading = ref(false)
const error = ref(false)

// 获取天气数据
const fetchWeather = async () => {
  loading.value = true
  error.value = false
  
  try {
    // 实际项目中应该调用真实的API
    // 这里模拟一个天气数据
    // const { data } = await get('/api/weather')
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    const data = {
      city: '北京',
      temperature: 26,
      weather: 'sunny',
      humidity: 40,
      icon: 'sunny'
    }
    
    weather.value = data
    emit('loaded', data)
  } catch (err) {
    console.error('获取天气数据失败:', err)
    error.value = true
    emit('error', err)
  } finally {
    loading.value = false
  }
}

// 根据天气状况获取图标
const getWeatherIcon = (weatherType) => {
  const iconMap = {
    sunny: 'sunny-o',
    cloudy: 'cloud-o',
    rainy: 'umbrella-circle',
    snowy: 'snowflake-o',
    windy: 'wind-circle-o',
    foggy: 'eye-o',
    thunder: 'lightning'
  }
  
  return iconMap[weatherType] || 'question-o'
}

onMounted(() => {
  if (props.autoLoad) {
    fetchWeather()
  }
})

// 暴露方法给父组件
defineExpose({
  fetchWeather
})
</script>

<style lang="scss" scoped>
.weather-widget {
  display: flex;
  align-items: center;
  padding: 4px 8px;
  background-color: var(--background-color);
  border-radius: 16px;
  cursor: pointer;
  
  .weather-icon {
    margin-right: 4px;
    color: var(--primary-color);
  }
  
  .weather-info {
    display: flex;
    flex-direction: column;
    font-size: 12px;
    line-height: 1.2;
    
    .temperature {
      font-weight: 500;
    }
    
    .city {
      font-size: 10px;
      color: var(--text-color-secondary);
    }
  }
}
</style> 